// games/ticTacToe.js

const ticTacToe = {
  PLAYER_LIMITE: 2,

  startGame: (room, io) => {
    console.log(`[井字棋] 房间 ${room.id} 游戏开始！`);
    // 初始化游戏状态
    room.gameState = {
      board: Array(9).fill(null),
      currentPlayer: room.players[0].id
    };

    room.playerInfo = {};

    const clientSocketIds = io.sockets.adapter.rooms.get(room.id);

    let bFirstPlayer = true;
    var curIndex = 0;

    if (clientSocketIds) 
    {
      for (const socketId of clientSocketIds) {
          const targetSocket = io.sockets.sockets.get(socketId);
          if (targetSocket) 
          {
                const isPlayer = curIndex < ticTacToe.PLAYER_LIMITE ? true : false;
                var playerMark = '';
                if (isPlayer) 
                {
                      playerMark = bFirstPlayer ? 'X' : 'O' ;
                      console.log("playerMark:", playerMark);
                }
                
                room.playerInfo[socketId] = {
                    index: curIndex,
                    mark: playerMark,
                    isPlayer: isPlayer
                };

                 targetSocket.emit('game_started', {
                        game: 'tic_tac_toe',
                        state: { 
                          common : room.gameState, // 共享的游戏状态
                          mark: playerMark, // 个性化的标记
                          isPlayer: isPlayer
                        }
                    });

                 bFirstPlayer = false;
                 curIndex = curIndex + 1;
          }
      }
    }

    console.log("room.playerInfo : ", room.playerInfo);
  },

  rejoinGame: (room, io, returnedSocketId) => {

    console.log("room.gameState : ", room.gameState);

    if (room.playerInfo)
    {
      if(room.playerInfo[returnedSocketId])
      {
        const targetSocket = io.sockets.sockets.get(returnedSocketId);
        if (targetSocket)
        {
          targetSocket.emit('game_started', {
            game: 'tic_tac_toe',
            state: { 
              common : room.gameState, // 共享的游戏状态
              mark: room.playerInfo[returnedSocketId].mark, // 个性化的标记
              isPlayer: room.playerInfo[returnedSocketId].isPlayer
            }
          });
        }
        else
        {
          console.log("targetSocket not found");
        }
      }
      else
      {
        console.log("room.playerInfo[returnedSocketId] not found");
      }
    }     
    else
    {
      console.log("room.playerInfo not found");
    }

   },

  handleAction: (room, socket, io, actionData) => {
    const { action, data } = actionData;
    switch (action) {
      case 'place_mark':
        if (room.gameState.currentPlayer !== socket.id) {
          return socket.emit('error', { message: '还没到你的回合！' });
        }
        console.log(`[井字棋] 玩家 ${socket.id} 在位置 ${data.position} 落子`);
        // 更新棋盘
        room.gameState.board[data.position] = data.mark;
        room.gameState.position = data.position

        console.log("room.gameState:", room.gameState);

        // 广播给所有玩家新的棋盘状态
        io.to(room.id).emit('game_state_updated', room.gameState);
        // 切换回合
        room.gameState.currentPlayer = room.players.find(p => p.id !== socket.id).id;
        break;
      default:
        console.log(`[井字棋] 未知动作: ${action}`);
        socket.emit('error', { message: '未知的井字棋动作' });
    }
  }
};

module.exports = ticTacToe;